package com.vhuan.self_discipline_service.serviceimpl.auth;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vhuan.common.constant.common.DeleteFlag;
import com.vhuan.common.constant.common.ExceptionCode;
import com.vhuan.common.domain.api.wxmini.WxminiLoginResponse;
import com.vhuan.self_discipline_service.domain.auth.dto.AuthRequest;
import com.vhuan.self_discipline_service.domain.auth.dto.AuthResponse;
import com.vhuan.self_discipline_service.domain.user.po.UserEntity;
import com.vhuan.self_discipline_service.domain.user.vo.UserVO;
import com.vhuan.self_discipline_service.manager.wxmini.WxminiManager;
import com.vhuan.self_discipline_service.mapper.user.UserMapper;
import com.vhuan.self_discipline_service.service.auth.AuthService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;


@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    private final WxminiManager wxminiManager;

    private final UserMapper userMapper;
    @Value("${jwt.key}")
    private String JWT_KEY;
    @Override
    public AuthResponse login(AuthRequest request) {
        //1.使用code调用微信登录接口，获取openid
        WxminiLoginResponse wxminiLoginResponse = wxminiManager.login(request.getCode());
        if (wxminiLoginResponse.getErrcode()!= ExceptionCode.WXMINI_API_SUCESS){
            throw new RuntimeException(wxminiLoginResponse.getErrmsg());
        }

        //2.判断用户是否注册
        //3.1.未注册，新增用户
        //3.2.已注册，返回token
        LambdaQueryWrapper<UserEntity> wrapper=new LambdaQueryWrapper<UserEntity>().
                eq(UserEntity::getDeleteFlag,DeleteFlag.NOT_DELETE).
                eq(UserEntity::getOpenid,wxminiLoginResponse.getOpenid());
        UserEntity userEntity=userMapper.selectOne(wrapper);
        UserVO userVO=new UserVO();
        if (userEntity==null){
            userEntity=new UserEntity();
            userEntity.setOpenid(wxminiLoginResponse.getOpenid());
            userMapper.insert(userEntity);
        }
        BeanUtil.copyProperties(userEntity,userVO);
        //jwt 生成token
        byte[] bytes = JWT_KEY.getBytes();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,1);
        String token = JWT.create()
                .setPayload("uid", userVO.getId())
                .setExpiresAt(instance.getTime())
                .setKey(bytes)
                .sign();

        return new AuthResponse(token,userVO);
    }
}
